package com.pubgnode.impl;

import com.pubgnode.constant.AuthConstants;
import com.pubgnode.factory.LoginStrategyFactory;
import com.pubgnode.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目自己的认证流程
 * 认证流程实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从上下文中获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //从请求头中获取登陆类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        //判断请求来自哪个系统
        //使用java的策略模式，对登陆的不同情况设置不同的策略，具体的策略写在LoginStrategy中
        /*if (AuthConstants.SYS_USER_LOGIN.equals(loginType)) {

            //商城后台管理系统流程

        }else{
            //商城用户购物系统流程
        }*/
        //判断是否存在用户登陆类型
        if(!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录，登陆类型不匹配");
        }
        //通过登陆策略工厂获取具体的登陆策略对象
        //优点：不论新增多少登陆方法，只需在具体的登陆策略实现类中添加，无需在此处添加代码
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance))  {
            throw new InternalAuthenticationServiceException("非法登录，登陆类型不匹配");
        }
        return instance.realLogin(username);

    }
}
